<template>
<div class="container">
  <!-- 面包屑 -->
   <SubBread></SubBread>
   <!-- 筛选区 -->
   <SubFilter @filter-change='filterChange'></SubFilter>
   <!-- 商品面板排序加列表 -->
   <div class="goods-list">
    <SubSort @sort-change="sortChange"></SubSort>
    <!-- 列表 -->
    <ul>
      <li v-for="item in goodList" :key="item.id">
        <goodsItem :goods="item"></goodsItem>
      </li>
    </ul>
    <!-- 加载loading -->
    <XtxInfiniteLoading @infinite='getData' :loading='loading' :finished="finished"></XtxInfiniteLoading>
   </div>

</div>
</template>

<script>
import SubBread from './components/sub-bread.vue'
import SubFilter from './components/sub-filter.vue'
import SubSort from './components/sub-sort.vue'
import goodsItem from './components/goodsItem'
import { findSubCatetoryGoods } from '@/api/category'
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
export default {
  name: 'SubHeader',
  components: {
    SubBread,
    SubFilter,
    SubSort,
    goodsItem

  },
  setup () {
    const route = useRoute()
    const loading = ref(false)
    const finished = ref(false)
    const goodList = ref([])
    let sendData = {
      page: 1,
      pagsize: 20
    }
    const getData = () => {
      loading.value = true
      sendData.categoryId = route.params.id
      findSubCatetoryGoods(sendData).then(({ result }) => {
        if (result.items.length) {
          goodList.value.push(...result.items)
          sendData.page++
        } else {
          finished.value = true
        }
        loading.value = false
      })
    }
    watch(() => route.params.id, (newValue) => {
      if (newValue && route.path === ('/topcategory/sub/' + newValue)) {
        goodList.value = []
        finished.value = false
        sendData = {
          page: 1,
          pagsize: 20
        }
      }
    })
    // 接收传来的排序属性数据
    const sortChange = (sortParams) => {
      console.log(sortParams)
      finished.value = false
      // 合并请求参数
      sendData = { ...sendData, ...sortParams }
      goodList.value = []
    }
    // 接收子组件传来属性选择的值
    const filterChange = (filterParams) => {
      finished.value = false
      sendData = { ...sendData, ...filterParams }
      sendData.page = 1
      goodList.value = []
    }

    return { getData, loading, finished, goodList, sortChange, filterChange }
  }

}
</script>

<style scoped lang="less">
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul{
     display: flex;
     flex-wrap: wrap;
     justify-content: space-between;
  }
}
</style>
